<template>
  <div>
    <button id="btn_control" @click="connectWebSocket">连接</button>
    <button @click="talk">说话</button>
    <div id="result"></div>
    <video
      id="player-container-id"
      width="414"
      height="570"
      preload="auto"
      playsinline
      webkit-playsinline
    ></video>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { get, useWebSocket } from '@vueuse/core'
import CryptoJS from 'crypto-js'
import Base64 from 'crypto-js/enc-base64'
import HmacSHA256 from 'crypto-js/hmac-sha256'
import VMS from './libs/vms-web-2d-sdk-2.0.0/sdk/vms-2d-web-sdk-2.0.0.esm.min.js';
import TCPlayer from 'tcplayer.js';
import 'tcplayer.js/dist/tcplayer.min.css';
import FlvJs from 'flv.js'


let iatWS;
let socket;
let resultText = "";
let resultTextTemp = "";
let countdownInterval;
var streamUrl = ''; // 替换为你的流地址

// var signalingServerUrl =''; // 替换为你的信令服务器地址
/**
 * 获取websocket url
 * 该接口需要后端提供，这里为了方便前端处理
 */
function getWebSocketUrl() {
  // 请求地址根据语种不同变化
  var url = "wss://avatar.cn-huadong-1.xf-yun.com/v1/interact";
  var host = "avatar.cn-huadong-1.xf-yun.com";
  var apiKey = 'a976b42c62ee640d88b119e7014b8053';
  var apiSecret = 'YmMwYjhmZGExYTExZWRmZGYyOGRmZGM3';
  var date = new Date().toGMTString();
  var algorithm = "hmac-sha256";
  var headers = "host date request-line";
  var signatureOrigin = `host: ${host}\ndate: ${date}\nGET /v1/interact HTTP/1.1`;
  var signatureSha = CryptoJS.HmacSHA256(signatureOrigin, apiSecret);
  var signature = CryptoJS.enc.Base64.stringify(signatureSha);
  var authorizationOrigin = `api_key="${apiKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`;
  var authorization = btoa(authorizationOrigin);
  url = `${url}?authorization=${authorization}&date=${date}&host=${host}`;
  return url;
}

let videoDom;
onMounted(() => {
  videoDom = document.getElementById('player-container-id')
})

function initVideo(url) {
  console.log(videoDom)
  console.log('streamUrl是：'+url);
        var flvPlayer = FlvJs.createPlayer({
            type: 'flv',
            url
        });
        flvPlayer.attachMediaElement(videoDom);
        flvPlayer.load();
        flvPlayer.play();
}

function connectWebSocket() {
  const websocketUrl = getWebSocketUrl();
  if ("WebSocket" in window) {
    iatWS = new WebSocket(websocketUrl);
  } else if ("MozWebSocket" in window) {
    iatWS = new MozWebSocket(websocketUrl);
  } else {
    alert("浏览器不支持WebSocket");
    return;
  }
  iatWS.onopen = (e) => {
    if (iatWS.readyState === WebSocket.OPEN) {
      console.log("WebSocket连接已建立。");}
      startHeartbeat(iatWS);
      const requestData = {
    header: {
        app_id: "4828f836",
        request_id: "001",
        ctrl: "start",
    },
    parameter: {
        avatar: {
            stream: {
                protocol: "flv",
                fps: 25,
                bitrate: 2000,
                alpha: 0
            },
            mask_region: "[0,51,1080,1347]",
            move_h: 12,
            move_v: 50,
            scale: 0.99,
            avatar_id: "110117007",
            width: 1280,
            height: 720
        },
        // tts: {
        //     vcn: "x4_yezi",
        //     speed: 50,
        //     pitch: 50,
        //     volume: 50
        // }
    }
}
    // 发送请求数据
    iatWS.send(JSON.stringify(requestData)) 
    setTimeout(() => {
      initVideo(streamUrl)
    }, 3000);
  };
  iatWS.onmessage = (e) => {
    const data =JSON.parse(e.data);
    console.log(data);
    if(data.payload.avatar.stream_url)
    streamUrl=data.payload.avatar.stream_url;
    //  initPlayer(streamUrl)
  };
  iatWS.onerror = (e) => {
    if (iatWS.readyState === WebSocket.CLOSING) {
      console.log("WebSocket连接出错");}
    console.error(e);
  };
  iatWS.onclose = (e) => {
    if (iatWS.readyState === WebSocket.CLOSED) {
      console.log("WebSocket连接已断开。");}
  };
}
//心跳函数
function startHeartbeat(ws) {
  const heartbeatMsg = {
    header: {
        app_id: "4828f836",
         ctrl: "ping",
        request_id: "001",
    },}
  // Send a heartbeat message every 30 seconds
  const interval = setInterval(function() {
    if (ws.readyState === WebSocket.OPEN) {
      ws.send(heartbeatMsg);
      console.log('Sent heartbeat:', heartbeatMsg);
    } else {
      clearInterval(interval); // Stop the heartbeat if the WebSocket is closed
    }
  }, 30000); 
}
  // ws.onmessage = function(event) {
  //   if (event.data === heartbeatMsg) {
  //   } else {
  //     console.log('Received message:', event.data);
  //   }
  // };
// }
function talk(){
  const requestData = {
    header: {
        app_id: "4828f836",
        ctrl:"text_driver",
        request_id: "001"
    },
    parameter: {
      avatar_dispatch: {
            interactive_mode: 1 // 0 追加; 1 打断
        }
    },
    payload: {
        text: {
            //驱动数字人播报的文本
            content: "请问你可以简要介绍一下你的技术背景和工作经历吗？我想了解一下你在IT行业的具体领域和项目经验。"
        }
    }
}
  iatWS.send(JSON.stringify(requestData))
}
</script>
<style scoped>
/* Your styles here */
</style>